import { formState, alertInfo, requestId, stuInfoSelector } from "../store";
import {
  useRecoilState,
  useSetRecoilState,
  useRecoilValueLoadable,
} from "recoil";
import { addStuApi, editStuByIdApi } from "../api/stuApi";
import { useNavigate, useParams } from "react-router-dom";
import { useEffect } from "react";

export default function AddOrEdit() {
  // 获取表单状态以及设置表单状态的方法
  const [form, setForm] = useRecoilState(formState);

  // 获取设置 alert 状态的方法
  const setAlertInfo = useSetRecoilState(alertInfo);

  const navigate = useNavigate();

  // 获取 requestId
  const [reqId, setReqId] = useRecoilState(requestId);

  // 获取 id，后期我们会判断这个 id 是否存在
  // 如果存在，说明是从编辑跳转过来的，如果不存在，说明是从新增跳转过来的
  const { id } = useParams();

  // 根据 id 来获取学生信息
  const stuInfoLoadable = useRecoilValueLoadable(stuInfoSelector(id));

  // 如果是从编辑跳转过来，那么涉及到一个信息的回填
  useEffect(() => {
    // 根据 id 获取对应 id 的学生详情
    if (id) {
      switch (stuInfoLoadable.state) {
        case "hasValue": {
          setForm(stuInfoLoadable.contents);
        }
      }
    } else {
      // 说明是新增进来的，那么我们就清空表单数据
      setForm({
        stuname: "",
        stuage: 0,
        phone: "",
        email: "",
        education: "本科",
        graduationschool: "",
        profession: "",
        profile: "",
      });
    }
  }, [id, stuInfoLoadable, setForm]);

  // 提交学生信息
  const submitStuInfo = (e: React.FormEvent<HTMLFormElement>) => {
    // 阻止表单默认行为
    e.preventDefault();

    // 这里在提交的时候就要分两种情况了
    if (id) {
      // 说明是编辑
      editStuByIdApi(id, form).then(() => {
        // 1. 设置 alert 的状态
        setAlertInfo({
          type: "success",
          message: "修改学生成功",
        });
      });
    } else {
      // 说明是新增
      addStuApi(form).then(() => {
        // 1. 设置 alert 的状态
        setAlertInfo({
          type: "success",
          message: "新增学生成功",
        });
      });
    }
    // 2. 更新 requestId
    setReqId(reqId + 1);

    // 3. 清空表单数据
    setForm({
      stuname: "",
      stuage: 0,
      phone: "",
      email: "",
      education: "本科",
      graduationschool: "",
      profession: "",
      profile: "",
    });

    // 4. 跳转到首页
    navigate("/");
  };

  return (
    <div className="container">
      {/* 标题 */}
      <h1 className="page-header">{id ? "修改学生" : "添加学生"}</h1>
      {/* 表单 */}
      <form onSubmit={submitStuInfo}>
        <div className="well">
          {/* 学生姓名 */}
          <div className="form-group">
            <label>学生姓名</label>
            <input
              type="text"
              className="form-control"
              placeholder="请输入学生姓名"
              value={form.stuname}
              onChange={(e) =>
                setForm((oldFormState) =>
                  Object.assign({}, oldFormState, { stuname: e.target.value })
                )
              }
            />
          </div>
          {/* 学生年龄 */}
          <div className="form-group">
            <label>学生年龄</label>
            <input
              type="text"
              className="form-control"
              placeholder="请输入学生年龄"
              value={form.stuage}
              onChange={(e) =>
                setForm((oldFormState) =>
                  Object.assign({}, oldFormState, {
                    stuage: Number(e.target.value),
                  })
                )
              }
            />
          </div>
          {/* 联系方式 */}
          <div className="form-group">
            <label>联系方式</label>
            <input
              type="text"
              className="form-control"
              placeholder="请输入联系方式"
              value={form.phone}
              onChange={(e) =>
                setForm((oldFormState) =>
                  Object.assign({}, oldFormState, { phone: e.target.value })
                )
              }
            />
          </div>
          {/* 邮箱地址 */}
          <div className="form-group">
            <label>邮箱地址</label>
            <input
              type="text"
              className="form-control"
              placeholder="请输入邮箱地址"
              value={form.email}
              onChange={(e) =>
                setForm((oldFormState) =>
                  Object.assign({}, oldFormState, { email: e.target.value })
                )
              }
            />
          </div>
          {/* 学历的下拉列表 */}
          <div className="form-group">
            <label>学历</label>
            <select
              className="form-control"
              value={form.education}
              onChange={(e) =>
                setForm((oldFormState) =>
                  Object.assign({}, oldFormState, {
                    education: e.target.value,
                  })
                )
              }
            >
              <option value="高中或职高">高中或职高</option>
              <option value="专科">专科</option>
              <option value="本科">本科</option>
              <option value="硕士">硕士</option>
              <option value="博士">博士</option>
            </select>
          </div>
          {/* 毕业院校 */}
          <div className="form-group">
            <label>毕业院校</label>
            <input
              type="text"
              className="form-control"
              placeholder="请输入毕业院校"
              value={form.graduationschool}
              onChange={(e) =>
                setForm((oldFormState) =>
                  Object.assign({}, oldFormState, {
                    graduationschool: e.target.value,
                  })
                )
              }
            />
          </div>
          {/* 职业 */}
          <div className="form-group">
            <label>职业</label>
            <input
              type="text"
              className="form-control"
              placeholder="请输入职业"
              value={form.profession}
              onChange={(e) =>
                setForm((oldFormState) =>
                  Object.assign({}, oldFormState, {
                    profession: e.target.value,
                  })
                )
              }
            />
          </div>
          {/* 个人简介 */}
          <div className="form-group">
            <label>个人简介</label>
            <textarea
              className="form-control"
              placeholder="请输入个人简介"
              value={form.profile}
              rows={15}
              onChange={(e) =>
                setForm((oldFormState) =>
                  Object.assign({}, oldFormState, {
                    profile: e.target.value,
                  })
                )
              }
            ></textarea>
          </div>
          <button className="btn btn-primary">
            {id ? "确认修改" : "确认新增"}
          </button>
        </div>
      </form>
    </div>
  );
}
